package com.zhuxin.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;

/**
 * Created by lzb on 2017/12/21.
 */
public class MessageListener implements GenericApplicationListener {
    private final Logger logger = LoggerFactory.getLogger(MessageListener.class);

    @Override
    public int getOrder() {
        return -2147483643;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) applicationEvent).getApplicationContext().getParent()== null) {
            logger.info("-------------------------------------------------------");
            logger.info("|                 应用启动完成...                       |");
            logger.info("-------------------------------------------------------");

//            new Thread(()->{
//                try {
//                    new NIOServer(8888).listen();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }).start();
//            MqttUtils.handle=MedicalApplication.ctx.getBean(MqttMessageHandle.class);
//            MqttUtils.handle=((ContextRefreshedEvent) applicationEvent).getApplicationContext().getBean(MqttMessageHandle.class);
        }else if(applicationEvent instanceof ApplicationEnvironmentPreparedEvent){
            ((ApplicationEnvironmentPreparedEvent) applicationEvent).getEnvironment().setIgnoreUnresolvableNestedPlaceholders(true);
        }else if(applicationEvent instanceof ServletWebServerInitializedEvent){//WebServerFactoryCustomizer、EmbeddedServletContainerInitializedEvent
            int port=((ServletWebServerInitializedEvent) applicationEvent).getWebServer().getPort();
            logger.info("WEB服务端口号:{}",port);
        }
    }

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return true;
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }
}
